import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'view-design';
import frameOut from "./frameOut";
import frameIn from "./frameIn";
import tools from 'public/tools/index.js'
Vue.use(VueRouter);

const handleFrameOut=function(setting){
    let map= frameOut.map(item=>{
        if(item.path==='/login'){
            item['component']=()=>import(`public/layout/login/${setting.frame.login}`)
        };
        return item;
    });
    return map;
}
const handleFrameIn=function(setting,store){
    frameIn[0]['component']=()=>import(`public/layout/frame/${setting.frame.layout}`);
    let menu=store.state.admin.layout.menu;
    let children=!!frameIn[0].children?frameIn[0].children:[];
    frameIn[0]['children']=handleChildren(menu,[]).concat(children);
    return frameIn;
}
const handleChildren=function(menu,array){
    menu.map(item=>{
        if(!!item.children&&item.children.length>0){
            array=handleChildren(item.children,array);
        }else{
            if(!item.redirect&&!!item.path){
                item['component']=()=>import(`@/pages${item.componentPath || item.path}`);
                array.push(item)
            }
        }
    });
    return array;
}
// 导出路由 在 main.js 里使用
const getRouter=function(Setting,store){
    let router = new VueRouter({
        routes:[...handleFrameOut(Setting),...handleFrameIn(Setting,store)],
        mode: Setting.routerMode,
        base: Setting.routerBase
    });

    /**
     * 路由拦截
     * 权限验证
     */
    router.$addRoutes = function (params){
        router.matcher = new VueRouter(
            {
                routes:[...frameOut],
                mode: router.options.mode,
                base: router.options.base
            }
        ).matcher;
        router.addRoute(params)
    }
    router.beforeEach((to, from, next) => {
        iView.LoadingBar.start();
        next();
    });

    router.afterEach(to => {
        // console.log("file: index.js:66  getRouter  to:", to)
        iView.LoadingBar.finish();
        // 多页控制 打开新的页面
        if(!!to.meta&&to.meta.menu){
            store.dispatch('admin/layout/addPage', to);
        }
        if (to.name === 'login') {
            tools.cookies.remove('token')
        }
        // 更改标题
        window.document.title=store.state.setting.frame.title[store.state.locale]+'-'+to.meta.title[store.state.locale];
        // 返回页面顶端。
        window.scrollTo(0, 0);
    });
    return router;
}


export { getRouter, handleChildren };
